package com.gingko.duominuo.ui.activity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.gingko.duominuo.R
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.utils.*
import com.gingko.duominuo.viewmodel.LoginViewModel
import com.gingko.duominuo.viewmodel.SplashViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

@AndroidEntryPoint
class SplashActivity : AppCompatActivity() {
    private val mViewModel by viewModels<SplashViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 用于第一次安装APP，进入到除这个启动activity的其他activity，点击home键，再点击桌面启动图标时，
        // 系统会重启此activity，而不是直接打开之前已经打开过的activity，因此需要关闭此activity
        if (!isTaskRoot) {
            val mainIntent = intent
            val action = mainIntent.action
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                finish()
                return
            }
        }
        setContentView(R.layout.activity_splash)
        pushActivity(this)
        initView()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
    }


    private fun initView() {
        setStatusBar()
        mViewModel.loadStateLiveData.observe(this) {
            checkPermissions()
        }
        mViewModel.loadNameMapping()
    }


    private fun setStatusBar() {
        StatusBarUtil.setTranslucent(this, 0);
        StatusBarUtil.setDarkMode(this);
    }

    private fun checkPermissions() {
        val permission = arrayOf(
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE
        )
        if (PermissionUtils.isGranted(this, *permission)) {
            runBlocking { delay(2000) }
        }

        LDPermission.from(this)
            .request(*permission) {
                if (!it) {
                    "文件权限被拒绝".toast()
                }
                val isLogin = runBlocking {
                    DataStoreHelper.isLogin()
                }
                if (isLogin) {
                    MainActivity.start(this)
                } else {
                    LoginActivity.start(this)
                }
                this@SplashActivity.finish()
            }

    }

    override fun onBackPressed() {
        exitAPP()
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.no_anim, R.anim.no_anim)
    }

    override fun onDestroy() {
        popActivity(this)
        super.onDestroy()
    }
}